package com.kaiwukj.android.ufamily.mvp.ui.page.home.home.active;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerHomeV20Component;
import com.kaiwukj.android.ufamily.di.module.HomeV20Module;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.ActiveEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.GlobalEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.ActiveParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.ActiveResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.home.contract.HomeV20Contract;
import com.kaiwukj.android.ufamily.mvp.ui.widget.SpaceItemDecoration;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ActiveFragment extends BaseMvpFragment<ActivePresenter> implements HomeV20Contract.ActiveView {


    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_active)
    RecyclerView rvActive;
    @BindView(R.id.empty_view)
    QMUIEmptyView emptyView;

    private ActiveAdapter mActiveAdapter;

    private int type;

    private int page = 1;
    private int pageSize = 10;

    private boolean isLoadingMore = false;

    private QMUIPopup mTypePop;
    private QMUIPopup mStatusPop;
    private int pType = 0;
    private int status = 0;

    private boolean isNeedRefresh = false;


    public static ActiveFragment newInstance(int type) {
        ActiveFragment fragment = new ActiveFragment();
        fragment.type = type;
        return fragment;
    }

    @OnClick({R.id.tv_status, R.id.tv_type})
    void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.tv_type:
                showTypePop(view);
                break;
            case R.id.tv_status:
                showStatusPop(view);
                break;
        }
    }

    public void showTypePop(View v) {
        if (mTypePop == null) {
            String[] items = new String[]{"全部", "官方", "管家", "物业"};
            List<String> data = new ArrayList<>();
            Collections.addAll(data, items);
            ArrayAdapter adapter = new ArrayAdapter(getContext(), R.layout.item_simple_list, data);
            mTypePop = QMUIPopups.listPopup(getContext(), ScreenUtils.getScreenWidth(),
                    SizeUtils.dp2px(180), adapter, (parent, view, position, id) -> {
                        tvType.setText(items[position]);
                        pType = position;
                        mTypePop.dismiss();
                        loadData();
                    });
            mTypePop.radius(0);
        }

        mTypePop.show(v);
    }

    public void showStatusPop(View v) {
        if (mStatusPop == null) {
            String[] items = new String[]{"全部", "报名中", "活动中", "已结束"};
            List<String> data = new ArrayList<>();
            Collections.addAll(data, items);
            ArrayAdapter adapter = new ArrayAdapter(getContext(), R.layout.item_simple_list, data);
            mStatusPop = QMUIPopups.listPopup(getContext(), ScreenUtils.getScreenWidth(),
                    SizeUtils.dp2px(180), adapter, (parent, view, position, id) -> {
                        tvStatus.setText(items[position]);
                        mStatusPop.dismiss();
                        status = position;
                        emptyView.show(true);
                        loadData();
                    });
            mStatusPop.radius(0);
        }

        mStatusPop.show(v);
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        super.setupFragmentComponent(appComponent);
        DaggerHomeV20Component.builder()
                .appComponent(appComponent)
                .homeV20Module(new HomeV20Module(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_active;
    }

    @Override
    protected void initView() {

        tvType.setText("全部");
        tvStatus.setText("全部");

        rvActive.setLayoutManager(new LinearLayoutManager(getContext()));
        rvActive.addItemDecoration(new SpaceItemDecoration(1));
        mActiveAdapter = new ActiveAdapter();
        rvActive.setAdapter(mActiveAdapter);

        //View emptyView = View.inflate(mContext, R.layout.empty_view_common_container, null);
        //  mActiveAdapter.setEmptyView(emptyView);

        mActiveAdapter.setOnItemClickListener((adapter, view, position) ->
                ARouter.getInstance().build(ARouterUrlKt.EventDetail)
                        .withInt("id", (int) adapter.getItemId(position))
                        .navigation());

        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadingMore = true;
                ++page;
                loadData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                loadData();
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    protected void initDataSupport() {
        super.initDataSupport();
        emptyView.show(true);
        loadData();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (isNeedRefresh) {
            isNeedRefresh = false;
            page = 1;
            loadData();
        }
    }

    @Override
    public void onFetchActive(@NotNull List<? extends ActiveResult> results) {
        emptyView.hide();
        if (isLoadingMore) {
            isLoadingMore = false;
            mActiveAdapter.addData(results);
            if (results.size() < pageSize) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore();
            }
        } else {
            mActiveAdapter.setList(results);
            refreshLayout.finishRefresh();
        }
        stateEmpty();
    }

    @Override
    public void onTaskErr(int taskId) {
        super.onTaskErr(taskId);
        stateEmpty();
    }

    private void stateEmpty() {
        if (mActiveAdapter == null || mActiveAdapter.getItemCount() == 0) {
            emptyView.show("暂没有活动", "");
        }
    }

    private void loadData() {
        ActiveParams params = new ActiveParams();
        params.setPage(page);
        params.setType(type);
        if (pType > 0) {
            params.setPubType(pType);
        }
        if (status > 0) {
            params.setStatus(status);
        }
        params.setPageSize(10);
        mPresenter.fetchActiveList(params);
    }

    @Override
    public void onFetchActiveDetail(@NotNull ActiveResult result) {

    }

    @Subscribe
    public void onGlobalEvent(GlobalEvent event) {
        if (event.getCode() == GlobalEvent.REFRESH) {
            isNeedRefresh = true;
        }
    }

    @Subscribe
    public void onActiveEvent(ActiveEvent event) {
        LogUtils.d("event------------------>" + GsonUtils.toJson(event));
        if (event.getCode() == ActiveEvent.JOIN) {
            mActiveAdapter.postJoin((Integer) event.getExt(), true);
        } else {
            mActiveAdapter.postJoin((Integer) event.getExt(), false);
        }
    }
}
